<template>
  <el-card class="box-card">
    <template #header>
      <div class="line">
        <div class="left">
          <span class="number" :class="current == 1 ? 'active' : 'bg'">
            <Check class="tubiao" v-if="current == 2" />
            <span v-else>1</span>
          </span>
          <span class="classInfo">填写课程信息</span>
        </div>
        <div class="line-frame"></div>
        <div class="left">
          <span class="number" :class="current == 2 ? 'active' : 'bg'">2</span>
          <span class="classInfo">上传视频</span>
        </div>
      </div>
    </template>
    <div class="main">
      <el-form
        v-show="current == 1"
        ref="ruleFormRefClass"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="课程标题" prop="name">
          <el-input
            v-model="ruleForm.name"
            style="width: 280px"
            maxlength="20"
            placeholder="请输入课程标题"
            show-word-limit
            type="text"
          />
        </el-form-item>
        <el-form-item label="课程封面" prop="cover">
          <upload
            class="classRot"
            :limit="1"
            :showTip="false"
            :custom="true"
            :modelValue="modelValueList"
            @update:modelValue="modelValue"
            limitatSize="infoBanner"
            :limitShowTip="true"
            :isShowTip="false"
          ></upload>
        </el-form-item>
        <el-form-item label="轮播图封面" prop="banner_img">
          <upload
            class="classRot Banner"
            :limit="1"
            :showTip="false"
            :custom="true"
            :modelValue="modelValueListBanner"
            @update:modelValue="modelValueBanner"
            limitatSize="banner"
            :limitShowTip="true"
            :isShowTip="false"
          ></upload>
        </el-form-item>
        <el-form-item label="是否推荐" prop="recommend">
          <el-row>
            <el-col :span="24" style="display: flex; align-items: center">
              <div>
                <!--  :disabled="ruleForm.recommend == 0" -->
                <el-radio-group
                  v-model="ruleForm.recommend"
                  :disabled="!ruleForm.banner_img"
                >
                  <!-- @change="choicesLimit" -->
                  <el-radio v-for="item in recommandList" :value="item.value">{{
                    item.label
                  }}</el-radio>
                </el-radio-group>
              </div>
              <div style="margin-left: 20px">
                *( <span style="color: red">选择推荐才会推荐课程</span> )*
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="课程描述" prop="describe">
          <el-input
            v-model="ruleForm.describe"
            style="width: 787px"
            :rows="2"
            type="textarea"
            placeholder="请输入课程描述"
          />
        </el-form-item>
        <el-form-item label="课程类型" prop="type">
          <el-checkbox-group v-model="ruleForm.type">
            <el-checkbox
              v-for="item in typeList"
              :label="item.name"
              :value="item.id"
            />
          </el-checkbox-group>
          <div class="add" @click="addCourseType">
            <div><Plus class="icon" /></div>
            <div>添加</div>
          </div>
        </el-form-item>
        <el-form-item label="观看权限" prop="jurisdiction">
          <el-row>
            <el-col :span="24" style="display: flex; align-items: center">
              <div>
                <!--  @change="choicesLimit" -->
                <el-radio-group v-model="ruleForm.viewing_permission">
                  <el-radio
                    v-for="item in jurisdictionList"
                    :value="item.value"
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </div>
              <div
                class="number"
                v-if="ruleForm.viewing_permission == '3'"
                style="margin-left: 30px; display: flex"
              >
                <el-form-item prop="courseDiscountPrice">
                  原价:
                  <el-input-number
                    v-model="ruleForm.courseDiscountPrice"
                    :min="0"
                    style="margin-right: 10px"
                    @change="handleChange"
                  />
                </el-form-item>

                <el-form-item prop="price">
                  优惠价:
                  <el-input
                    v-model="ruleForm.price"
                    style="
                      width: 110px;
                      height: 34px;
                      margin-left: 5px;
                      --el-input-focus-border-color: var(--primary-color);
                    "
                    placeholder="请输入价格"
                    show-word-limit
                    type="number"
                    step="any"
                    :min="0"
                  />
                </el-form-item>
                <span class="sm"
                  >元 ，收费课程被订购时，将收取
                  <span class="color">课程销售金额的30%</span>
                  作为客单费，从机构余额中扣除。</span
                >
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="课程标识" prop="sign">
          <el-row>
            <el-col :span="24" style="display: flex; align-items: center">
              <div>
                <el-radio-group v-model="ruleForm.sign">
                  <!-- @change="choicesLimit" -->
                  <el-radio v-for="item in signList" :value="item.value">{{
                    item.label
                  }}</el-radio>
                </el-radio-group>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="课程介绍(移动端)" label-width="70px">
          <!-- <Editor :height="400" @update:modelValue="editorChange"></Editor> -->
          <UEditorPlus
            :id="id1"
            style="width: 900px; z-index: 0"
            @update:modelValue="editorChange"
            v-model="ruleForm.blurb_m"
          />
        </el-form-item>
        <el-form-item label="课程介绍(PC端)" label-width="70px">
          <!-- <Editor :height="400" @update:modelValue="editorPhoneChange"></Editor> -->
          <UEditorPlus
            :id="id2"
            style="width: 900px; z-index: 0"
            @update:modelValue="editorPhoneChange"
            v-model="ruleForm.blurb_pc"
          />
        </el-form-item>
      </el-form>
      <div v-if="current == 2">
        <div style="display: flex">
          <!-- v-hasPermi="['operation:editClass:addVideos']" -->
          <el-button
            @click="saveUploadVideo(1)"
            class="btn_1"
            style="
              color: var(--primary-color);
              border: 1px solid var(--primary-color);
              background-color: #fff;
            "
            >上传视频</el-button
          >
          <!-- v-hasPermi="['operation:editClass:videosClass']" -->
          <el-button
            @click="addVideo()"
            class="btn_1"
            style="
              color: var(--primary-color);
              border: 1px solid var(--primary-color);
              background-color: #fff;
            "
            >从视频库添加</el-button
          >
        </div>
        <div
          style="
            background-color: #ccc;
            position: relative;
            margin-top: 30px;
            z-index: 0;
          "
        >
          <draggable
            @editOperation="editOperation"
            @saveDelele="saveDelele"
            :list="list"
            :status="ruleForm"
            @updateList="updateList"
          ></draggable>
        </div>
      </div>
    </div>
    <div class="footer">
      <el-button
        v-if="current == 1"
        class="btn isbtn"
        style="width: 86px"
        type="primary"
        @click="submitForm()"
        >下一步</el-button
      >
      <div v-if="current == 2">
        <el-button
          :class="list?.length <= 0 ? 'activeBg' : ''"
          :disabled="!list?.length"
          style="
            width: 86px;
            background-color: var(--primary-color);
            color: #fff;
          "
          @click="submitForm('发布')"
          >发布</el-button
        >
        <el-button
          @click="backBtn"
          class="btn_1"
          style="
            color: var(--primary-color);
            border: 1px solid var(--primary-color);
            background-color: #fff;
          "
          >上一步</el-button
        >
      </div>
    </div>
  </el-card>
  <!-- 抽屉  -->
  <Drawer v-model="drawer" title="添加课程类型">
    <template #center>
      <div class="boxOne">
        <div class="left">
          <div class="search">
            <el-input
              v-model="params.name"
              style="width: 237px"
              placeholder="在视频库中搜索"
              clearable
            />
            <!-- v-hasPermi="['operation:editClass:add']" -->
            <el-button class="btn" @click="changeInput">添加</el-button>
          </div>
        </div>
        <div class="txt">最多添加12个类型</div>
        <tables
          :typeList="typeList"
          :off="off"
          @saveEdit="saveEdit"
          @saveDelBtn="saveDelBtn"
          @sumPrice="sumPrice"
          @selectionChangePrice="selectionChangePrice"
        ></tables>
        <!-- dialog弹框 -->
        <Dialog v-model="editClassvitied" title="修改课程类型" width="420">
          <template #center>
            <el-form :model="form" label-position="top">
              <el-form-item label="类别:" style="margin-top: 20px">
                <el-input
                  v-model="form.name"
                  style="
                    width: 370px;
                    height: 40px;
                    --el-input-focus-border-color: var(--primary-color);
                  "
                  maxlength="6"
                  placeholder="请输入课程类别"
                  show-word-limit
                  type="text"
                />
              </el-form-item>
              <el-form-item label="价格:">
                <el-input
                  v-model="form.typePrice"
                  style="
                    width: 370px;
                    height: 40px;
                    --el-input-focus-border-color: var(--primary-color);
                  "
                  placeholder="请输入价格"
                  show-word-limit
                  type="text"
                />
              </el-form-item>
            </el-form>
          </template>
          <template #footer>
            <div class="dialog-footer">
              <el-button
                @click="editClassvitied = false"
                style="
                  background-color: #fff;
                  color: var(--primary-color);
                  border: 1px solid var(--primary-color);
                "
                >取消</el-button
              >
              <el-button type="primary" @click="saveClick"> 确定 </el-button>
            </div>
          </template>
        </Dialog>
        <Dialog v-model="delDialog" title="删除提醒" center width="420">
          <template #center
            ><div style="line-height: 80px">
              类型删除后，将无法通过该类型筛选视频，确定删除吗？
            </div></template
          >
          <template #footer>
            <el-button
              class="btn"
              style="background-color: #fff; color: #666"
              @click="delDialog = false"
              >取消</el-button
            >
            <el-button type="primary" @click="delRemind">确定</el-button>
          </template>
        </Dialog>
      </div>
    </template>
    <template #footer>
      <div class="goods">
        <div>
          总价:<span style="color: red">{{ totalPrice }}元</span>
        </div>
        <div style="color: #e6a23c">温馨提示:设置分类购买须到主页面配置</div>
        <div>
          折扣价:<el-input
            v-model="form.discountedPrice"
            style="
              width: 110px;
              height: 40px;
              margin-left: 10px;
              --el-input-focus-border-color: var(--primary-color);
            "
            placeholder="请输入价格"
            @change="changeDiscountedPrice"
            show-word-limit
            type="number"
          />
        </div>
        <el-button type="primary" @click="saveTypeClass">保存</el-button>
      </div>
    </template>
  </Drawer>
  <!-- 视频上传弹窗 -->
  <Dialog
    v-model="dialogFormVisible"
    title="上传视频"
    custom-class="stylecustom"
  >
    <template #center>
      <div class="center">
        <videoList
          class="videoP"
          ref="fileUploader"
          @eventVideo="eventVideo"
          @progress="progress"
          @updateData="updateData"
        ></videoList>
      </div>
      <p class="info_s">
        建议上传视频：比例16：9，分辨率：1280*720，视频大小不超过2G
      </p>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="startUpload"> 开始上传 </el-button>
      </div>
    </template>
  </Dialog>
  <!-- 从视频库中添加 -->
  <Drawer
    v-model="drawerVideo"
    title="视频库"
    style="padding: 0"
    custom-class="custom-drawer"
  >
    <template #center>
      <div class="drawer_container">
        <div>
          <div class="box">
            <div class="left">
              <div class="search">
                <el-input
                  v-model="videoForm.search"
                  style="width: 237px"
                  placeholder="在视频库中搜索"
                  clearable
                  @change="slectSearch"
                />
                <el-button class="btn" @click="slectSearch">搜索</el-button>
              </div>
            </div>
            <div class="right">
              <!-- v-hasPermi="['operation:editClass:addVideos']" -->
              <el-button
                class="video"
                type="primary"
                @click="saveUploadVideo(2)"
                >上传视频</el-button
              >
            </div>
          </div>
          <div class="drawerTable">
            <my-table
              :columns="columnDrawer"
              :tableData="drawerDataList"
              :selection="true"
              @selectionChange="selectionChange"
            >
              <template #imgs="{ row }">
                <ProcessedImage
                  v-if="!row.cover"
                  :src="'https://b.gaokaow.cc/no-cover.png'"
                  params="imageView2/1/w/100/h/100"
                />
                <ProcessedImage
                  v-else
                  :src="row.cover"
                  params="imageView2/1/w/100/h/100"
                />
              </template>
              <template #operation="{ row }">
                <div>
                  <span class="editicon" @click="editInfo(row)"
                    ><EditPen
                      style="width: 1em; height: 1em; margin-right: 8px"
                  /></span>
                  <span class="editicon" @click="detele(row)"
                    ><Delete style="width: 1em; height: 1em; margin-right: 8px"
                  /></span>
                </div>
              </template>
            </my-table>
          </div>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="videoForm.page"
            v-model:page-size="videoForm.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="videoForm.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button
          @click="drawerVideo = false"
          style="background-color: #fff; color: #4e5969"
          >取消</el-button
        >
        <el-button
          :disabled="selectDataList.length <= 0"
          :class="selectDataList.length <= 0 ? 'activeBg' : ''"
          type="primary"
          @click="videoDrawerBtn"
          >确定</el-button
        >
      </div>
    </template>
  </Drawer>
  <!-- 修改弹窗 -->
  <Dialog title="修改" v-model="dialogVisible" width="560">
    <template #center>
      <el-form
        ref="ruleFormRef"
        :model="ruleFormVideo"
        :rules="rules"
        class="demo-ruleForm"
        status-icon
        style="margin-top: 30px"
      >
        <el-form-item label="视频标题" prop="name">
          <el-input v-model="ruleFormVideo.name" style="width: 280px" />
        </el-form-item>
        <el-form-item label="视频封面" prop="pic">
          <div class="center img2">
            <ImagUploa
              width="280px"
              :isShowTip="false"
              :isShow="false"
              :limit="1"
              :modelValue="modelValueListDrawer"
              @update:modelValue="modelValueDrawer"
            ></ImagUploa>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveVideoEditBtn"> 确定 </el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup>
import videoList from '@/components/videoUpload/index.vue';
import upload from '@/components/ImageUpload2/index';
import Drawer from './componts/video';
import tables from './componts/table';
import Dialog from '../classRoom/components/dialog.vue';
import ImagUploa from '@/components/ImageUpload2/index.vue';
import myTable from '../classRoom/components/tableList.vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, onMounted, reactive, computed, watch } from 'vue';
import draggable from './componts/draggable.vue';
import classRoom from '@/modules';
import { formatDate } from '@/utils/index';
import router from '@/router';
import { omit } from 'lodash';
// import href from '@/modules';
// const { bannerInfoApi } = href;
import href from '@/modules';
const { ZYbannerInfoApi } = href;
const {
  saveApi,
  classTypeListApi,
  addClassTypeApi,
  deLclassTypeApi,
  saveClassTypetApi,
  infoApi,
  videoListApi,
  addClassRoomPriceApi,
  saveVideoApi,
} = classRoom; //  saveVideoApi,,
const route = useRoute();
const current = ref(1);
const ruleFormRefClass = ref(null);
const ruleFormRef = ref(null);
const drawer = ref(false);
const drawerVideo = ref(false);
const fileUploader = ref(null);
const ids = ref('');
const idInfo = ref('');
const drawerDataList = ref([]);
// 修改课程弹窗
const dialogFormVisible = ref(false);
//删除课程弹窗
const delDialog = ref(false);
const dialogVisible = ref(false);
const editClassvitied = ref(false);
const selectDataList = ref([]);
const id1 = ref('etidorNewGood1');
const id2 = ref('etidorNewGood2');
const videotableDataListGround = ref([]);
const typeVideos = ref('');
const selectChangeId = ref('');
const modifyRow = ref([]);
const title = ref('');
const schedule = ref('');
const classTypeId = ref('');
const off = ref('');
//拖拽
const totalPrice = ref('');
const list = ref([]);
const form = reactive({
  id: '',
  name: '',
  typePrice: '',
  discountedPrice: '',
});
const videoForm = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  search: '',
  id: '',
});
const ruleForm = reactive({
  id: 0, //d为0 时，新增；其他为修改
  name: '',
  storeId: JSON.parse(localStorage.getItem('userDateInfo'))?.storeId,
  cover: '',
  banner_img: '',
  sort: '',
  sign: '',
  type: [],
  viewing_permission: '',
  blurb_m: '',
  blurb_pc: '',
  describe: '',
  price: '',
  courseDiscountPrice: 0,
  status: 1,
  videos: '',
  videoSort: '',
  recommend: '',
});
let params = ref({
  page: 1,
  pageSize: 10,
  name: '',
});
const pcDescription = ref(''); // 移动端介绍信息
const appDescription = ref(''); // 电脑详细信息
const typeList = ref([]);
const videoSortDatalist = ref([]);
const ruleFormVideo = ref({
  name: '',
  pic: '',
  cover: '',
  id: '',
});
//图片
const modelValueList = ref([]);
const modelValueListBanner = ref([]);
// 拖拽列表图片
const modelValueListDrawer = ref([]);
// const agreement1 = '';
// const agreement2 = '';

const rules = reactive({
  name: [{ required: true, message: '请输入课程标题', trigger: 'blur' }],
  cover: [{ required: true, message: '请输入课程封面', trigger: 'blur' }],
  // banner_img: [{ required: true, message: '请输入轮播封面', trigger: 'blur' }],
  describe: [{ required: true, message: '请输入课程描述', trigger: 'blur' }],
  pic: [{ required: true, message: '请输入课程封面', trigger: 'blur' }],
  courseDiscountPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === null || value === '') {
          callback(new Error('请输入原价'));
        } else if (value <= 0) {
          callback(new Error('原价必须大于 0'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  price: [
    { required: true, message: '请输入优惠价', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === null || value === '') {
          callback(new Error('请输入优惠价'));
        } else if (value <= 0) {
          callback(new Error('优惠价必须大于 0'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});
// 右侧抽屉数据
const columnDrawer = ref([
  { prop: 'imgs', label: '视频封面' },
  { prop: 'name', label: '视频名称' },
  { prop: 'create_time', label: '上传时间' },
  // { prop: 'operation', label: '操作' },signList
]);
const jurisdictionList = ref([
  {
    label: '免费',
    value: '1',
  },
  {
    label: 'VIP',
    value: '2',
  },
  {
    label: '付费',
    value: '3',
  },
]);
const signList = ref([
  {
    label: '选修',
    value: '1',
  },
  {
    label: '必修',
    value: '2',
  },
]);
const recommandList = ref([
  {
    label: '不推荐',
    value: 0,
  },
  {
    label: '推荐',
    value: 1,
  },
]);
// 金额限至
// const choicesLimit = (val) => {
//   console.log('val:', val);
// };
const changeDiscountedPrice = (val) => {
  console.log('val:', val);
  if (val <= 0) {
    form.discountedPrice = 0;
  }
};
// 是否有图片的计算属性
const hasImage = computed(() => !!ruleForm.banner_img);

// 监听 hasImage 的变化
watch(hasImage, (newValue) => {
  if (!newValue) {
    ruleForm.recommend = 0; // 如果图片被删除，则重置推荐选项为“不推荐”
  }
});
// 搜索
const slectSearch = () => {
  videoForm.value.page = 1;
  getVideoTableData();
};

const startUpload = () => {
  if (fileUploader.value) {
    fileUploader.value.triggerUpload(); // 调用子组件中的 triggerUpload 方法
  }
};
const progress = ({ stepNumber }) => {
  if (stepNumber == 100) {
    dialogFormVisible.value = false;
  }
};
const updateData = () => {
  setTimeout(() => {
    getVideoTableData();
  }, 100);
};
const handleSizeChange = (val) => {
  videoForm.value.pageSize = val;
  getVideoTableData();
};
const handleCurrentChange = (val) => {
  videoForm.value.page = val;
  getVideoTableData();
};

// 多选框
const selectionChange = (val) => {
  selectDataList.value = val;
  videotableDataListGround.value = val;
  // 遍历数组，并将每个对象的 value 属性转换为字符串
  // 使用 map 方法获取所有 value 属性值组成的数组
  const valuesArray = selectDataList.value.map((item) => item.id);
  // 将数组中的所有值用逗号连接成一个字符串
  selectChangeId.value = valuesArray.join(',');
};
const videoDrawerBtn = () => {
  let str;
  if (ruleForm.videos != '') {
    str = ruleForm.videos + ',' + selectChangeId.value;
  } else {
    str = selectChangeId.value;
  }
  // 首先将字符串分割成数组，并移除空格
  const array = str.split(',').map((num) => num.trim());
  // 然后使用 Set 去重
  // const uniqueArray = [...new Set(array)];
  // 最后将去重后的数组转换回字符串
  ruleForm.videos = array.join(',');
  const mergedArray = [...list.value, ...videotableDataListGround.value];

  // 使用 reduce 去重，基于 id 字段
  const result = mergedArray.reduce((acc, current) => {
    // 检查当前项的 id 是否已存在于 acc 数组中
    if (!acc.some((item) => item.id === current.id)) {
      acc.push(current);
    }
    return acc;
  }, []);
  ruleForm.videos = result.map((item) => item.id).join(',');
  list.value = result;

  if (list.value.length) {
    ruleForm.videoSort = JSON.stringify(list.value);
  }
  drawerVideo.value = false;
};
//图片上传
const modelValue = (val) => {
  modelValueList.value = val;
  ruleForm.cover = val;
};
// 拖拽列表编辑图片
const modelValueDrawer = (val) => {
  ruleFormVideo.value.pic = val;
  modelValueListDrawer.value = val;
  ruleFormVideo.value.cover = val;
};
const modelValueBanner = (val) => {
  modelValueListBanner.value = val;
  ruleForm.banner_img = val;
};
// 上传视频数据
const eventVideo = (val, id, url, durationTime) => {
  if (typeVideos.value == 1) {
    const create_time = formatDate(val.file.lastModifiedDate);
    const name = val.file.name;
    const cover = null;
    const add = url;
    const video_time = durationTime;
    list.value.push({ create_time, name, cover, id, add, video_time });
    const ids = list.value.map((item) => item.id).join(',');
    ruleForm.videos = ids;
    ruleForm.videoSort = JSON.stringify(list.value);
  }
};
const saveTypeClass = async () => {
  if (
    ((totalPrice.value != '' || totalPrice.value == 0) &&
      form.discountedPrice != '') ||
    form.discountedPrice == 0
  ) {
    const data = await addClassRoomPriceApi({
      classTypeId: classTypeId.value,
      price: totalPrice.value,
      discountedPrice: form.discountedPrice,
    });
    if (data.code == 20000) {
      ElMessage({
        message: data.msg,
        type: 'success',
      });
    }
  }

  drawer.value = false;
};
// 编辑课程类别
const saveClassApi = async () => {
  const { id, name, typePrice } = form;
  try {
    const res = await saveClassTypetApi({
      id,
      name,
      typePrice,
    });
    if (res.code == 20000) {
      ElMessage({
        message: res.msg,
        type: 'success',
      });
      getListData();
    }
  } catch (err) {
    console.log(err);
  }
};
const saveClick = () => {
  if (form.name == '') {
    return;
  }
  editClassvitied.value = false;
  saveClassApi();
};
//编辑课程类型
const saveEdit = (row) => {
  editClassvitied.value = true;
  Object.assign(form, row);
};
//删除课程类型
const delApi = async () => {
  try {
    const res = await deLclassTypeApi({ id: ids.value });
    if (res.code == 20000) {
      ElMessage({
        message: res.msg,
        type: 'success',
      });
      getListData();
    }
  } catch (err) {
    console.log(err);
  }
};
const delRemind = () => {
  delApi();
  delDialog.value = false;
};
const saveDelBtn = (row) => {
  delDialog.value = true;
  ids.value = row.id;
};
const sumPrice = (val) => {
  // 提取所有 id 并转换为字符串
  classTypeId.value = val.map((item) => item.id).join(',');
  totalPrice.value = val.reduce(
    (sum, item) => sum + parseFloat(item.typePrice),
    0
  );
};
const selectionChangePrice = (val) => {
  if (typeList.value.length == val.length) {
    // 提取所有 id 并转换为字符串
    classTypeId.value = val.map((item) => item.id).join(',');
    totalPrice.value = val.reduce(
      (sum, item) => sum + parseFloat(item.typePrice),
      0
    );
  } else {
    totalPrice.value = '';
  }
};
//添加课程类型
const addApi = async () => {
  try {
    const res = await addClassTypeApi({ name: params.value.name });
    if (res.code == 20000) {
      ElMessage({
        message: res.msg,
        type: 'success',
      });
      getListData();
      params.value.name = '';
    }
  } catch (err) {
    console.log(err);
  }
};
const changeInput = () => {
  if (params.value.name == '') {
    ElMessage({
      message: '请输入课程类型',
      type: 'warning',
    });
    return;
  }
  const isTrue = typeList.value.some((item) => item.name === params.value.name);
  if (isTrue) {
    ElMessage.error('标签名重复');
    return;
  } else {
    addApi();
  }
};
//视频库编辑
const saveVideoEditInfo = async () => {
  modifyRow.value.name = ruleFormVideo.value.name;
  modifyRow.value.cover = modelValueListDrawer.value;
  // ruleForm.cover = ruleFormVideo.value.cover;
  const { id, cover, name } = ruleFormVideo.value;
  const res = await saveVideoApi({ id, cover, name });
  if (res.code == 20000) {
    ElMessage({
      type: 'success',
      message: res.msg,
    });
  }
  dialogVisible.value = false;
};

// 修改视频封面
const saveVideoEditBtn = async () => {
  await ruleFormRef.value.validate((value) => {
    if (value) {
      saveVideoEditInfo();
    }
  });
};
// 删除视频
const saveDelele = (row) => {
  ElMessageBox.confirm('确认要删除吗？', '确认提示?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 从视频列表中过滤掉当前行的 id
      list.value = list.value.filter((item) => item.id !== row.id);
      ruleForm.id = videoSortDatalist.value.id;
      // 将 videos 字符串转为数字数组
      const idsToDelete = ruleForm.videos.split(',').map(Number);
      // 检查 row.id 是否在 idsToDelete 中
      if (idsToDelete.includes(row.id)) {
        // 创建一个新的数组，移除 row.id
        const updatedIds = idsToDelete.filter((id) => id != row.id);
        // 你可以选择将 updatedIds 储存回 ruleForm 或其他使用它的地方
        ruleForm.videos = updatedIds.join(','); // 如果需要将其转换为逗号分隔的字符串
      }
    })
    .catch(() => {});
};
// 价格
const handleChange = (val) => {
  console.log(val, '价格');
};
// 移动端输入信息
const editorChange = (val) => {
  pcDescription.value = val;
};
// 电脑端输入信息
const editorPhoneChange = (val) => {
  appDescription.value = val;
};
//上传视频
const saveUploadVideo = (type) => {
  typeVideos.value = type;
  dialogFormVisible.value = true;
};
const addCourseType = () => {
  drawer.value = true;
};
//视频仓库列表
const getVideoTableData = async () => {
  try {
    const { data } = await videoListApi(omit(videoForm.value, 'total'));
    drawerDataList.value = data.data;
    videoForm.value.total = data.total;
  } catch (err) {
    console.log(err);
  }
};
//从视频库中添加
const addVideo = () => {
  getVideoTableData();
  drawerVideo.value = true;
};
// 新增课时
const saveAddApi = async (params) => {
  const res = await saveApi(params);
  if (res.code == 20000) {
    ElMessage({
      type: 'success',
      message: res.msg,
    });
    router.push({ path: '/operation/classRoom' });
  }
};
// 拖拽排序
const updateList = ({ list }) => {
  ruleForm.videoSort = JSON.stringify(list);
};
const submitForm = async (type) => {
  await ruleFormRefClass.value.validate((value) => {
    if (value) {
      current.value = 2;
      if (ruleForm.id == 0) {
        if (list.value?.length) {
          const formData = {
            ...ruleForm,
            type: Array.isArray(ruleForm.type) ? ruleForm.type.join(',') : '',
          };
          saveAddApi(formData);
        }
      } else {
        if (type == '发布') {
          const formData = {
            ...ruleForm,
            type: Array.isArray(ruleForm.type) ? ruleForm.type.join(',') : '',
          };
          if (title.value == '编辑') {
            ruleForm.videoSort = JSON.stringify(list.value);
            const formData = {
              ...ruleForm,
              type: Array.isArray(ruleForm.type) ? ruleForm.type.join(',') : '',
            };
            saveAddApi(formData);
          } else {
            saveAddApi({
              id: formData.id,
              videos: formData.videos,
              videoSort: JSON.stringify(list.value),
            });
          }
        }
      }
    }
  });
};
// 上一步
const backBtn = () => {
  current.value = 1;
};
const getListData = async () => {
  const { data } = await classTypeListApi(params.value);
  form.discountedPrice = data.priceInfo.discountedPrice ?? '0.00';
  typeList.value = data.data;
  if (typeList.value.length) {
    classTypeId.value = typeList.value.map((item) => item.id).join(',');
    totalPrice.value = typeList.value.reduce((sum, item) => {
      const price = parseFloat(item.typePrice) || 0; // 若无效则视为0
      return sum + price;
    }, 0);
  }
};
//编辑弹窗
const editOperation = (row) => {
  modifyRow.value = row;
  modelValueListDrawer.value = row.cover;
  ruleFormVideo.value.pic = row.cover;
  Object.assign(ruleFormVideo.value, row);
  // 这里不知是否可以注释
  // ruleForm.cover = row.cover;
  // list.value.map((item) => {item.id == row.id});
  dialogVisible.value = true;
};
// 详情数据
const detailApi = async () => {
  try {
    const { data } = await infoApi({ id: idInfo.value });
    data.type = data.type ? data.type.split(',').map(Number) : [];
    videoSortDatalist.value = data;
    ruleForm.cover = data.cover ? data.cover : '';
    data.price = parseFloat(data.price);
    data.courseDiscountPrice = Number(data.courseDiscountPrice);
    // 拖拽排序数据
    data.viewing_permission = data.viewing_permission.toString();
    Object.assign(ruleForm, data);
    modelValueList.value = [data.cover];
    modelValueListBanner.value = data.banner_img ? [data.banner_img] : [];
    const uniqueData = data.videoSort ? JSON.parse(data.videoSort) : '';
    list.value = uniqueData;
  } catch (err) {
    console.log(err);
  }
};
// 判断是否显示价格设置
const bannerInfo = async () => {
  const data = await ZYbannerInfoApi();
  off.value = data.data.off;
};
onMounted(async () => {
  route.query.id ? (current.value = route.query.id) : '';
  videoForm.value.id = route.query.typeId;
  getListData();
  if (route.query.ids) {
    idInfo.value = route.query.ids;
    title.value = '编辑';
    videoForm.value.id = route.query.ids;
    await detailApi();
  }
  if (route.query.typeId) {
    schedule.value = '课节';
    idInfo.value = route.query.typeId;
    ruleForm.id = route.query.typeId;
    await detailApi();
  }
  bannerInfo();
});
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: end;
  width: 100%;
}
:deep(.edui-editor .edui-editor-toolbarbox) {
  position: static;
}
:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: var(--primary-color);
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: var(--primary-color) !important;
  border-color: var(--primary-color);
}
:deep(.u-editor-content) {
  height: 500px !important;
}
.videoP :deep(.el-upload) {
  width: 382px !important;
  height: 20% !important;
}
:deep(.edui-editor) {
  z-index: 0 !important;
  width: 800px !important;
  height: 500px !important;
}
:deep(.edui-editor):nth-child(1) {
  margin-bottom: 500px !important;
}
:deep(.el-upload__tip-1) {
  display: none;
}
:deep(.el-upload) {
  width: 360px !important;
  height: 180px;
}
.classRot :deep(.el-upload) {
  width: 280px !important;
}
:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}
:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: var(--primary-color);
}
:deep(.el-input) {
  --el-input-focus-border: none;
}
:deep(.el-dialog__header) {
  height: 40px !important;
  min-height: 30px !important;
}
:deep(.el-upload) {
  width: 280px !important;
}
:deep(.el-card__header) {
  border-bottom: none;
}
:deep(.el-button > span) {
  font-weight: none;
}

:deep(.el-button) {
  height: 42px;
  color: #fff;
  background-color: var(--primary-color);
}
.isbtn :deep(.el-button--primary.is-disabled) {
  background-color: #94bfff;
  border-color: #94bfff;
}
.img2 :deep(.el-upload--picture-card) {
  width: 280px !important;
}
.search {
  :deep(.el-input__wrapper) {
    box-shadow: none;
  }
}

.search {
  :deep(.el-input) {
    height: 40px;
    border: 1px solid var(--primary-color);
  }
}
.box-card {
  padding-bottom: 28px;
  flex: 1;
  overflow-y: auto;
  background-color: rgb(252, 252, 252);
  position: relative;
  .tubiao {
    text-align: center;
    width: 1em;
    height: 1em;
    color: var(--primary-color);
  }
  .number {
    // margin-left: 30px;
    text-align: center;
    .sm {
      display: inline-block;
      margin-left: 5px;
      .color {
        color: rgb(255, 51, 0);
      }
    }
  }
  .main {
    margin: 0 20px;
    .add {
      display: flex;
      align-items: center;
      margin-left: 25px;
      color: var(--primary-color);
      cursor: pointer;
    }
    .icon {
      width: 1em;
      height: 1em;
      margin-right: 8px;
      margin-top: 10px;
    }
  }
  .line {
    display: flex;
    align-items: center;
    padding: 40px 0 30px 0;
    .left {
      .number {
        display: inline-block;
        width: 28px;
        height: 28px;
        border-radius: 50%;
        color: #000;
        line-height: 28px;
        text-align: center;
        margin-right: 10px;
        background-color: #f5f9ff;
      }
      .active {
        color: #fff;
        background-color: var(--primary-color);
      }
      .bg {
        background-color: #f5f9ff;
      }
      .classInfo {
        color: #666;
      }
    }
    .left:first-child {
      margin-left: 40px;
    }
    .line-frame {
      height: 1px;
      width: 116px;
      background-color: #e5e6eb;
      margin: 0 10px;
    }
  }
  .footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    height: 80px;
    background-color: rgb(255, 255, 255);
    box-shadow: -10px 0 30px 0 rgba(0, 0, 0, 0.05);
    padding: 20px 0 20px 40px;
    z-index: 1000;
    .btn {
      height: 40px;
      background-color: var(--primary-color);
    }
  }
}
.boxOne {
  padding-top: 24px;
}
.search {
  display: inline-block;
  .btn {
    margin-left: -2px;
  }
}
.txt {
  color: rgb(134, 144, 156);
  font-size: 12px;
  margin-top: 10px;
  margin-bottom: 10px;
}
.center {
  margin: 20px 0;
}
.el-upload__tip_txt {
  font-size: 12px;
  color: #4e5969;
  margin-top: 7px;
}

.box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 24px;
}
.drawer_container {
  position: relative;
}
// .footer_btn {
//   position: fixed;
//   bottom: 0;
//   width: 47%;
//   height: 100px;
//   border-top: 1px solid #ccc;
//   .bottom_btn {
//     position: absolute;
//     top: 50%;
//     right: 0;
//     transform: translateY(-50%);
//   }
// }
.search :deep(.el-input) {
  height: 40px;
  border-radius: none !important;
  border: 1px solid var(--primary-color);
}
.search :deep(.el-button) {
  height: 42px !important;
  background: var(--primary-color);
  color: #fff;
  border-radius: none !important;
  width: 86px !important;
}
.btn {
  margin-left: 10px;
  color: #fff;
  background: var(--primary-color);
}
.right {
  :deep(.el-button--primary) {
    background: var(--primary-color);
  }
}
.video {
  height: 42px;
}
.drawerTable {
  margin-top: 20px;
}
.editicon {
  cursor: pointer;
  font-size: 20px;
  color: #1d2129;
}
.editicon:first-child {
  margin-right: 10px;
}
.pagination {
  margin-top: 20px;
}
.cancel:hover {
  border: 1px solid var(--primary-color);
  background-color: #4080ff;
}
.activeBg {
  opacity: 0.5;
}
</style>
<style lang="scss">
.Banner .el-upload-list--picture-card .el-upload-list__item {
  width: 800px !important; /* 使用 !important 确保样式覆盖 */
}
.Banner .el-upload {
  width: 800px !important;
}
/* 你可以通过类选择器或id选择器设置具体的样式 */
.vue-ueditor-wrap {
  height: 600px; /* 设置固定高度 */
}
.stylecustom {
  :deep(.el-dialog__header) {
    height: 30px !important;
    min-height: 30px !important;
  }
}

.el-table .el-table__row {
  cursor: move; /* 显示手指图标以表示可拖拽 */
}
.info_s {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  font-size: 12px;
  color: #4e5969;
}
.goods {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
